package data

import (
	"math"
	"strconv"
	"strings"
	"time"
)

const FormatLayout = "2006-01-02 15:04:05"
const Format_yyyyMMddHHmm = "2006-01-02 15:04"
const Format_yyyyMMddHH = "2006-01-02 15"

//获得一天前时间
func GetYesterdayStart(date time.Time) time.Time {
	timeStr := date.Format("2006-01-02")
	t, _ := time.ParseInLocation("2006-01-02", timeStr, time.Local)
	return t.AddDate(0, 0, -1)
}

//
func GetYesterdayEnd(date time.Time) time.Time {
	timeStr := date.Format("2006-01-02")
	t2, _ := time.ParseInLocation("2006-01-02", timeStr, time.Local)
	return t2
}

//时间转string
func GetDate(date time.Time) string {
	return date.Format("2006-01-02")
}

//
func StdFormat(date time.Time) string {
	return FormatDate(date, FormatLayout)
}

func FormatDate(date time.Time, layout string) string {
	return date.Format(layout)
}

//返回单位
func FormatTime(duration int64) string {
	if duration == 0 {
		return "0"
	}
	result := ""

	unix := time.Unix(1593532800, 0)

	unix = unix.Add(time.Millisecond * time.Duration(duration))

	if unix.Day() > 1 {
		result = result + strconv.Itoa(unix.Day()-1) + "d"
	}
	if unix.Hour() > 0 {
		result = result + strconv.Itoa(unix.Hour()) + "h"
	}
	if unix.Minute() > 0 {
		result = result + strconv.Itoa(unix.Minute()) + "m"
	}
	if unix.Second() > 0 {
		result = result + strconv.Itoa(unix.Second()) + "s"
	}

	return result
}

func ConvertTime(timestamp int64) time.Time {
	return time.Unix(0, timestamp*1000000)
}

func ParseLocation(name string, timeStr string) (time.Time, error) {
	if l, err := time.LoadLocation(name); err != nil {
		return time.Time{}, err
	} else {
		lt, _ := time.ParseInLocation(FormatLayout, timeStr, l)
		return lt, nil
	}
}

//有A表，B表，需要做分页，A表必须，B表在缺失数据时候使用，计算b表的pageSize和pageNum
func ComputePage(length, pageNum, pageSize int) (int, int) {
	if pageNum*pageSize <= length {
		return 0, 0
	} else if pageNum*pageSize > length && ((pageNum-1)*pageSize) < length {
		return 0, pageSize*pageNum - length
	} else {
		return pageSize*(pageNum-1) - length, pageSize
	}
}

//将float64转成精确的int64
func Wrap(num float64, retain int) int64 {
	return int64(num * math.Pow10(retain))
}

//将int64恢复成正常的float64
func Unwrap(num int64, retain int) float64 {
	return float64(num) / math.Pow10(retain)
}

//精准float64
func WrapToFloat64(num float64, retain int) float64 {
	return num * math.Pow10(retain)
}

//精准int64
func UnwrapToInt64(num int64, retain int) int64 {
	return int64(Unwrap(num, retain))
}

//计算带有乘号的阈值
func ComputeThreshold(threshold string) (float64, error) {
	threshold = strings.ReplaceAll(threshold, " ", "")
	if strings.Contains(threshold, "*") {
		thresholds := strings.Split(threshold, "*")
		var threshold2 float64 = 1
		for _, t := range thresholds {
			t2, err := strconv.ParseFloat(t, 64)
			if err != nil {
				return 0, err
			}
			threshold2 = threshold2 * t2
		}
		return threshold2, nil
	} else {
		threshold2, err := strconv.ParseFloat(threshold, 64)
		if err != nil {
			return 0, err
		}
		return threshold2, nil
	}
	return 0, nil
}
